<?php

class AdminController extends Controller
{
	// 当前操作表
	protected $tableName;
	// 当前表的model类
	protected $model;
	// 过滤列表
	protected $map = array();

    public function __construct()
    {
        C('tpl_theme','');
        C('layout',true);
        C('layout_name','/application/admin/view/public_layout.html');
    }

	public function init()
	{
		session_start();
		if (empty($_SESSION['admin'])) {
			//未登录
			$this->redirect(U('admin.public.login'));
		} else {
			$this->username = $_SESSION['admin']['username'];
			$this->userid = $_SESSION['admin']['userid'];
		}
		if ($this->tableName){
			$this->model=M($this->tableName);
		}
	}

	protected function getMap()
	{
		$map=array();
		$this->assign('searchkey','');
		foreach ($this->model->getTableField() as $val) {
			if (isset($_REQUEST ['searchkey']) && $_REQUEST['searchtype']==$val && $_REQUEST ['searchkey'] != '') {
				$this->assign('searchtype',$_REQUEST['searchtype']);
				$this->assign('searchkey',$_REQUEST['searchkey']);
				//拼装搜索条件
				if (false!==strpos($_REQUEST ['searchkey'],'*') or false!==strpos($_REQUEST ['searchkey'],'?'))
					$map [$val] = array('like',str_replace(array('*', '?'), array('%', '_'), $_REQUEST ['searchkey']));
				else
					$map [$val]=array('like','%'.$_REQUEST ['searchkey'].'%');
			}
		}
		$this->map=array_merge($this->map,$map);
	}

	protected function _list()
	{
		$order=empty($_REQUEST['order'])?$this->model->getPk():$_REQUEST['order'];
		$sort=empty($_REQUEST['sort'])?'desc':$_REQUEST['sort'];
		$page=empty($_REQUEST['page'])?1:$_REQUEST['page'];
		$rows=empty($_REQUEST['rows'])?C('ADMIN_LISTNUM',null,20):$_REQUEST['rows'];
		$count=$this->model->where($this->map)->count();
		$list=(array)$this->model->where($this->map)->limit($rows)->page($page)->order($order.' '.$sort)->select();
		if (method_exists($this,'_data')){
			$list=$this->_data($list);
		}
		$this->assign('list',$list);
		$this->assign('pagestr',$this->showpage($count,$rows,$page));
		$this->assign('totalnum',$count);
		$this->assign('order',$order);
		$this->assign('sort',$sort);
		$this->assign('rows',$rows);
	}

	public function indexAction()
	{
		$tpl=(func_num_args()>0)?func_get_arg(0):'';
		$this->getMap();
		$this->_list();
		cookie('admin_listurl',__SELF__);
		$this->display($tpl);
	}

	public function addAction()
	{
		$this->display();
	}

	public function insertAction()
	{
		$res=$this->model->insert($_POST);
		if ($res){
			$this->success('添加成功',cookie('admin_listurl'));
		}else{
			$this->error("添加失败[{$this->model->getLastSql()}]");
		}
	}

	public function editAction()
	{
		$id=I('get.id','en','');
		$info=$this->model->where(array($this->model->getPk()=>$id))->find();
		if ($info){
			$this->assign('info',$info);
			$this->display();
		}else{
			$this->error('找不到指定的信息');
		}
	}

	public function updateAction()
	{
		$id=I('post.id','en','');
		$res=$this->model->where(array($this->model->getPk()=>$id))->update($_POST);
		if ($res===0 or $res===1){
			//$this->success('修改成功',cookie('admin_listurl'));
			$this->success('修改成功');
		}else{
			$this->error("修改失败[{$this->model->geterror()}]");
		}
	}

	/**
	 * 分页输出
	 * @param $totalnum
	 * @param $perpage
	 * @param $nowpage
	 * @param string $url
	 * @return string
	 */
	public function showpage($totalnum,$perpage,$nowpage,$url=''){
		if ($url===''){
			$params=$_GET;
			unset($_GET['m'],$_GET['c'],$_GET['a'],$_GET['s'],$_GET['t']);
			$params=array_merge($params,array('page'=>'__PAGE__'));
			$url=U();
			foreach($params as $k=>$v){
				$url.='/'.$k.'/'.$v;
			}
		}
		$totalpage=ceil($totalnum/$perpage);
		if ($totalpage<6){
			$start=1;
			$end=$totalpage;
		}elseif ($nowpage<3){
			$start=1;
			$end=5;
		}elseif ($totalpage<$nowpage+2){
			$start=$totalpage-4;
			$end=$totalpage;
		}else{
			$start=$nowpage-2;
			$end=$nowpage+2;
		}
		if ($totalpage<1) return '';
		$str="<i>{$totalnum} 条记录 {$nowpage}/{$totalpage} 页</i>";
		if ($nowpage==1){
			$str.='<a href="javascript:;" onclick="return false;" class="disable">上一页</a> ';
		}else{
			$str.='<a href="'.str_replace('__PAGE__',1,$url).'">首页</a> ';
			$str.='<a href="'.str_replace('__PAGE__',($nowpage-1),$url).'">上一页</a> ';
		}
		for ($i=$start;$i<=$end;$i++){
			if ($i==$nowpage){
				$str.='<a href="'.str_replace('__PAGE__',$i,$url).'" class="current">'.$i.'</a> ';
			}else{
				$str.='<a href="'.str_replace('__PAGE__',$i,$url).'">'.$i.'</a> ';
			}
		}
		if ($nowpage==$totalpage){
			$str.='<a href="javascript:;" onclick="return false;" class="disable">下一页</a> ';
		}else{
			$str.='<a href="'.str_replace('__PAGE__',($nowpage+1),$url).'" >下一页</a> ';
			$str.=' <a href="'.str_replace('__PAGE__',$totalpage,$url).'">尾页</a> ';
		}
		return $str;
	}

	// 修改某个字段的值
	public function changeAction()
	{
		$table = I('get.table','en','');
		$field = I('get.field','en','');
		$id = I('get.id','en','');
		$var = I('get.var','en','');
		$d = M($table);
		//获得要更改的主键
		$key = $d->getPk();
		if ($d->where(array($key => $id))->save(array($field => $var))) {
			$this->success('ok','',true);
		} else {
			$this->error('更新数据出错['.$d->getLastSql().']','',true);
		}
	}

	//批量操作
	public function multiAction()
	{
		$type=I('post.dooperate','str','en');
		switch($type){
			case 'order'://排序
				$idArr=array_map('intval',$_POST['id']);
				$orderArr=array_map('intval',$_POST['order']);
				foreach($idArr as $id){
					if ($id>0 && !empty($orderArr[$id])){
						$this->model->where(array($this->model->getPk()=>$id))->save(array('ordernum'=>$orderArr[$id]));
					}
				}
				break;
			case 'pass'://批量通过
				$idArr=array_map('intval',$_POST['id']);
				$this->model->where(array($this->model->getPk()=>array('in',$idArr)))->save(array('status'=>1));
				break;
			case 'hide'://批量删除 伪
				$idArr=array_map('intval',$_POST['id']);
				$this->model->where(array($this->model->getPk()=>array('in',$idArr)))->save(array('status'=>-1));
				break;
			case 'ban'://批量禁用
				$idArr=array_map('intval',$_POST['id']);
				$this->model->where(array($this->model->getPk()=>array('in',$idArr)))->save(array('status'=>0));
				break;
			case 'del'://批量删除
				$idArr=array_map('intval',$_POST['id']);
				if($this->tableName=='archive'){
					$this->model->where(array($this->model->getPk()=>array('in',$idArr)))->delete($this->module);
				}else{
					$this->model->where(array($this->model->getPk()=>array('in',$idArr)))->delete();
				}
				break;
		}
		$this->success('操作成功！',cookie('admin_listurl'));
	}

	/**
	 * 检测关键词是否存在
	 */
	public function checkkeyAction()
	{
		$res=$this->model->where(array($this->model->getPk()=>array('<>',I('post.id')),'key'=>$_POST['key']))->field($this->model->getPk())->find();
		if($res){
			$this->error('这个关键词已经被使用了');
		}else{
			$this->success('恭喜，这个关键词可以使用');
		}
	}

	public function getinfoAction()
	{
		$id=I('get.id');
		$info=$this->model->where(array($this->model->getPk()=>$id))->find();
		($info)?$this->success($info):$this->error('未找到该信息');
	}

    public function changestatusAction()
    {
        $id=I('post.id','int',0);
        $v=I('post.v','int',0);
        if ($this->model->where(array($this->model->getPk()=>$id))->update(array('status'=>$v))){
            $this->success('修改成功');
        }else{
            $this->error('修改状态失败',$this->model->getlastsql());
        }
    }

    public function delAction()
    {
        $id = I('request.id', 'int', 0);
        if ($id) {
            $this->model->where(array($this->model->getPk() => $id))->delete();
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
}